import {error} from "@/utils/msg";
import {toCamelCase} from "@/utils/util";
import {post, get} from "@/utils/http/httpUtils";
import {getNewArrDataToolBtn, updateSortRowCall} from "@/utils/TableSortUtil";
import {DefaultMethods} from "@/mixins/VTMixin/DefaultMethods";
import {mapActions} from 'vuex';

export const OTMixinBodyMethods = {
    mixins: [DefaultMethods],
    emits: ['handleOperationClick', 'toolbarBtnClick', 'initComponents', 'selectRowChange'],
    methods: {
        /**
         * 自定义表单方法
         * @returns {*}
         */
        customerForm(show) {
            this.toggleFormDisplay()
            this.table.formConfig.show = show == true;
            return this.table.formConfig;
        }, /**
         * 搜索隐藏/显示
         */
        toggleFormDisplay() {
            this.table.formConfig.show = !this.table.formConfig.show;
            // 获取组件的根 DOM 元素
            const rootEl = this.$refs[this.table.ref].$el;

            // 查询第一个子标签是否为 vxe-grid--form-wrapper
            const formWrapperEl = rootEl.querySelector('.vxe-grid--form-wrapper');
            if (formWrapperEl) {
                // 查询 formWrapperEl 下的第一个 form 标签
                const formEl = formWrapperEl.querySelector('form');
                if (formEl) {
                    // 获取 form 标签的当前 display 样式
                    const currentDisplay = window.getComputedStyle(formEl).display;

                    // 根据当前 display 样式设置新的样式
                    if (currentDisplay === 'none') {
                        // 如果当前是 none，则移除 display 样式（设置为空字符串）
                        formEl.style.display = '';
                    } else {
                        // 否则设置为 none
                        formEl.style.display = 'none';
                    }
                }
            }
        }, eventMethod(events) {
            console.log(this.events, events)
        }, /**
         * 选中回调
         */
        selectRowChange() {
            let rows = this.getSelectRows();
            if (!rows) {
                return;
            }
            this.pagination.selectionRowsLength = rows.length;
            this.setToolBtn('batchDelete', 'disabled', rows.length == 0)
            rows = this.selectBox == 1 ? rows[0] : rows;
            if (this.events['selectRowChange']) {
                this.events['selectRowChange'](rows)
            }
            this.$emit("selectRowChange", rows)
        }, /**
         * 初始化列左边
         * @param columns
         * @param type
         * @returns {*}
         */
        initBodyLeftColumn(columns, type) {
            if (type == 1) {
                columns.unshift({type: 'seq', minWidth: 55, width: 60, title: '序号', fixed: 'left'});
            }
            if (this.selectBox == 2) {
                columns.unshift({type: 'checkbox', width: 45, showOverflow: false, fixed: 'left'});
            } else if (this.selectBox == 1) {
                columns.unshift({type: 'radio', width: 45, showOverflow: false, fixed: 'left'});
            }
            return columns;
        }, /**
         * 切换表格最大化/还原
         */
        zoomEvent() {
            if (this.$table) {
                this.$table.zoom()
                this.isMaximized = this.$table.isMaximized()
            }
        }, initToolBtn(toolBut) {
            let obj = undefined;
            for (let i = 0; i < toolBut.length; i++) {
                let toolButElement = toolBut[i];
                toolButElement.disabled = toolButElement.defaultDisabled == 1
                toolButElement.show = toolButElement.defaultShow == 1
                if (toolButElement.code == 'sortable') {
                    toolButElement.values = false;
                    obj = JSON.parse(JSON.stringify(toolButElement))
                    obj.id = obj.id + "_sortable";
                    obj.name = "调整完成";
                    obj.code = "sortableOk";
                    obj.icon = "vxe-icon-check";
                    obj.show = false;
                    obj.disabled = true;
                    obj.index = i + 1;
                }
            }
            if (obj) {
                toolBut.splice(obj.index, 0, obj)
            }
            this.toolBtn = toolBut;
        }, initOperationBtn(operationBtn) {
            this.operationBtn = operationBtn;
            let length = this.operationBtn.length;
            if (length != 0) {
                let width = 35;
                if (this.table.operationWidth) {
                    width = this.table.operationWidth;
                } else {
                    for (let o of this.operationBtn) {
                        width += (o.name.length * (35 - length) + (o.icon !== undefined ? 5 : 0));
                    }
                }
                this.table.columns.push({
                    title: '操作', width: width, fixed: "right", slots: {default: 'operate'}
                })
            }
        }, initTree({tree, treeId, treeParentId}) {
            if (tree == 1) {
                this.table.treeConfig = {
                    show: true,
                    transform: false,
                    indent: 15,
                    reserve: tree,
                    rowField: treeId,
                    parentField: treeParentId,
                    treeId: treeId,
                    treeParentId: treeParentId,
                    iconClose: "vxe-icon-arrow-right",
                    iconOpen: "vxe-icon-arrow-down"
                }
                this.table.rowConfig.keyField = treeId;
            }
        }, initFormMainList(formMainList) {
            this.formMainList = formMainList
        }, async doSetComponents(customUrl, method, props, multipleProps) {
            //this.customUrl = markRaw(customUrl);
            this.customUrl = customUrl;
            await this.$nextTick(async () => {
                if (multipleProps == '1' || multipleProps == true) {
                    doCallback(this.$refs.components[method], props)
                } else if (multipleProps == '2') {
                    doCallback2(this.$refs.components[method], props)
                } else {
                    this.$refs.components[method](props)
                }
            })
        }, setComponent(url, method, props, multipleProps) {
            if (url.indexOf("@") == 0) {
                this.$emit('initComponents', {url: url, method: method, props: props, multipleProps: multipleProps})
            } else {
                this.doSetComponents(require(`@/${url}`).default, method, props, multipleProps)
            }

        }, async toolbarBtnClick(code) {
            if (code == "batchDelete") {
                this.batchRemove();
                this.$emit('toolbarBtnClick', code)
                return
            } else if (code == 'download') {
                this.setComponent("components/ol-dialog-excel", "open", {
                    id: this.tableConfig.id, selectData: this.pagination.selectionRowsLength >= 1 ? '2' : '1'
                })
                return
            } else if (code == 'upload') {
                let {json} = this.getToolBtn(code)
                    if(json){
                        json = json.replace(/([{,]\s*)([a-zA-Z0-9_]+)(\s*:)/g, '$1"$2"$3').replace(/:(\s*)'([^']+)'(\s*[,}])/g, ':$1"$2"$3'); // 修正字符串值
                        json = JSON.parse(json)
                    }
                this.setComponent("components/ol-dialog-import", "open", {
                    column: JSON.parse(JSON.stringify(this.table.columnSource)), tableConfigId: this.tableConfig.id,json:json
                })
                return
            } else if (code == 'sortable') {
                this.sortableClick();
                return;
            } else if (code == 'sortableOk') {
                this.loading['sortableOk'] = true;
                this.sortableOkClick();
                return;
            }
            let customFunction = this.getToolBtn(code).customFunction;
            if (customFunction != undefined) {
                eval(customFunction);
            } else if (code == 'add') {
                this.showForm(code);
            }
            this.$emit('toolbarBtnClick', code)

        }, sortableClick() {
            for (let toolBtn of this.toolBtn) {
                if (toolBtn.code == 'sortable') {
                    toolBtn.values = !toolBtn.values;
                    this.loading['sortableOk'] = false;
                    this.setToolBtn('sortableOk', 'show', toolBtn.values);
                    toolBtn.start = 999999;
                    toolBtn.end = -1;
                    if (toolBtn.values) {
                        if (toolBtn.beforeFunction == undefined || toolBtn.beforeFunction == '' || toolBtn.beforeFunction.split(",") < 2) {
                            error("排序字段未配置,请在做工具栏按钮配置中配置参数1(sort,id)");
                            return;
                        }
                        toolBtn.updateData = {};
                        toolBtn.$elm = updateSortRowCall(this.$table, (oldIndex, newIndex) => {
                            let start = Math.min(oldIndex, newIndex)
                            let end = Math.max(oldIndex, newIndex)
                            toolBtn.start = Math.min(start, toolBtn.start)
                            toolBtn.end = Math.max(end, toolBtn.end)
                            this.setToolBtn('sortableOk', 'disabled', false)
                            this.table.data = getNewArrDataToolBtn(oldIndex, newIndex, this.table.data, toolBtn)
                        })
                    } else if (toolBtn.$elm) {
                        this.setToolBtn('sortableOk', 'disabled', true)
                        toolBtn.$elm.destroy();
                        toolBtn.$elm = undefined;
                        this.query();
                    }
                    return;
                }
            }
        }, sortableOkClick() {
            for (let toolBtn of this.toolBtn) {
                if (toolBtn.code == 'sortable') {
                    let url;
                    this.loading['sortableOk'] = true;
                    this.table.loading = true;
                    let params = {
                        updateList: []
                    };
                    //sort,id  排序字段,更新主键
                    let kw = toolBtn.beforeFunction.split(",");
                    if (toolBtn.alterFunction) {
                        url = toolBtn.alterFunction;
                    } else {
                        url = '/online/crud/batchModify';
                        params.tableConfigId = this.tableConfig.id;
                    }
                    //这里肯定只有一个值
                    for (let key of Object.keys(toolBtn.updateData)) {

                        if (toolBtn.alterFunction) {
                            let kv = {};
                            kv[kw[1]] = key
                            kv[kw[0]] = toolBtn.updateData[key]
                            params.updateList.push(kv);
                        } else {
                            let columnAndValueMap = {};
                            let whereMap = {};
                            whereMap[kw[1]] = key
                            columnAndValueMap[kw[0]] = toolBtn.updateData[key]
                            params.updateList.push({
                                columnAndValueMap, whereMap
                            });
                        }
                    }
                    post(this.http, url, params).then((status) => {
                        if (status) {
                            this.query();
                            this.setToolBtn('sortableOk', 'disabled', true);
                        }
                    }).finally(() => {
                        this.loading['sortableOk'] = false;
                        this.table.loading = false;
                    })
                }
            }
        }, showRender(descCode, url, title) {
            get(this.http, '/online/formDesigner/getOne', {descCode: descCode}, undefined, true).then(d => {
                let data = {
                    type: 1,
                    saveUrl: url,
                    title: title,
                    form: JSON.parse(d.formJson),
                    tableConfigId: this.tableConfig.id
                }
                this.$refs["form"].init(data, false)
            });
        }, showForm(code, formData) {
            if (!formData) {
                formData = {};
            }
            let form = this.formMainList[code];
            if (!form) {
                return;
            }
            let formJsonStr = form.formJson[form.formMain.designer == 0 ? 'optionJson' : 'customJson'];
            let data = {
                type: form.formMain.designer,
                saveUrl: form.formMain.saveUrl,
                requestType: form.formMain.requestType,
                updateKey: form.formMain.updateKey,
                formData: formData,
                theme: this.theme,
                code: code,
                form: JSON.parse(formJsonStr),
                tableConfigId: this.tableConfig.id
            }
            this.$refs["form"].init(data)
        }, async handleOperationClick(o) {
            let {obj, row} = o;
            if (obj.customFunction) {
                eval(obj.customFunction);
            } else if (obj.code == "delete") {
                this.remove(o);
            } else if (obj.code == 'edit') {
                this.showForm(obj.code, row)
            }
            this.$emit("handleOperationClick", o)
        },
        ...mapActions('dict', {dictInit: 'init', dictRefresh: 'refresh'}),
        ...mapActions('dictType', {dictTypeInit: 'init', dictTypeRefresh: 'refresh'}),

    },
    created() {
        this.dictInit(this.http)
        this.dictTypeInit(this.http)
    }
}

function rowCamelCase(o) {
    let obj = {};
    for (let key of Object.keys(o)) {
        if (key == 'XROWKEY') {
            continue;
        }
        let k = key;
        if (re(key)) {
            k = key.substring(3)
        }
        obj[toCamelCase(k)] = o[key];
    }
    return obj;
}

function re(k) {
    let reg = /^t\d_/;
    return reg.test(k)
}

function doCallback(fn, args) {
    for (let arg of args) {
        fn.apply(this, arg);
    }
}

function doCallback2(fn, args) {
    fn.apply(this, args);
}
